package com.yuebu.bluetoothbandsdk;

import android.app.Activity;
import android.bluetooth.BluetoothGattCharacteristic;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.text.format.Formatter;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.yuebu.bluetoothbandsdk.adapter.MessageAdapter;
import com.yuebu.bluetoothbandsdk.utils.SPUtils;
import com.yuebu.yuebubtlib.BandCommAgent;
import com.yuebu.yuebubtlib.PushType;
import com.yuebu.yuebubtlib.bean.DeviceParameterBean;
import com.yuebu.yuebubtlib.bean.DeviceTimeBean;
import com.yuebu.yuebubtlib.bean.PersonalInfoBean;
import com.yuebu.yuebubtlib.bean.SedentaryAlarmBean;
import com.yuebu.yuebubtlib.exception.BLEException;
import com.yuebu.yuebubtlib.listener.BluetoothSignalListener;
import com.yuebu.yuebubtlib.util.BLEFileUtil;
import com.yuebu.yuebubtlib.util.BLELogUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;

public class TestActivity extends AppCompatActivity {
    private static final String TAG = "TestActivity";
    private BandCommAgent bandCommAgent;
    private Button setParameter;
    private Button takePhoto;
    private Button getBattery;
    private Button clearData;
    private Button getDeviceMacAddress;
    private Button getFW;
    private Button getDeviceTime;
    private RecyclerView recyclerView;
    private MessageAdapter messageAdapter;
    private Button btn_sedentary_alarm;
    private Button setUserInfo;
    private Button getSportAndSleepData;
    private Button findDevice;
    private Button getRealStep;
    private Button getSportAndSleepDataAllDay;
    private Button readRealHeartRate;
    private Button appPushMsgToDevice;
    private Button setDeviceTime;
    private Button unbindMac;
    private EditText etWeek;
    private EditText etHour;
    private EditText etAllDayWeek;
    private EditText etStartHour;
    private EditText etEndHour;
    private EditText etDetectionTime;
    private EditText etRepeatCycle;
    private Button btnControlDevice;
    private Button closeDevice;
    private Button restartDevice;
    private Button openRemind;
    private Spinner remindType;
    private TextView progressInfo;
    //提醒开关所选条目的位置
    private int selectedType = 0;
    //消息推送类型
    private int msgType = 0;
    //ota升级类型
    private int updateType = 0;
    private EditText etMessageTitle;
    private EditText etMessageContent;
    private Spinner messageType;
    private ProgressBar progressBar;
    private Button checkOTAFile;
    private Button otaUpdate;
    private EditText etFilePath;
    private static final int REQUEST_GET_FILE = 100;
    private int actionType = 0;
    byte[] ReadData = null;
    private int SendPacketID = 0;
    private int SendPacketAllNum = 0;
    private int SendSectionID = 0;
    private boolean spinner_doingfun_sel = false;
    int CRC = 0;
    int SECTION_CRC = 0;
    final int MAX_TRANS_COUNT = 15;
    final int MAX_TRANS_COUNT_V30 = 20;
    final int MAX_TRANS_SECTIONALL_COUNT = 5120;
    final int MAX_TRANS_SECTIONALL_PACKET_COUNT = MAX_TRANS_SECTIONALL_COUNT / 20;
    private int MAX_TRANS_SECTIONALL_SIZE = 0;
    final byte ERR_COMMAND_SUCCESS = 0x00;
    final byte ERR_COMMAND_FAILED = 0x01;
    final byte EVT_COMMAND_COMPLETE = (0x0E);
    final byte ACTIONTYPE_CMD_FW_WRITE_START = 0x01;
    final byte ACTIONTYPE_CMD_FW_WRITE_END = 0x02;
    final byte ACTIONTYPE_CMD_FW_ERASE = 0x03;
    final byte ACTIONTYPE_CMD_FW_WRITE = 0x04;
    final byte ACTIONTYPE_CMD_FW_UPGRADE = 0x05;
    final byte ACTIONTYPE_CMD24K_FW_ERASE = 0x06;
    final byte ACTIONTYPE_CMD24K_FW_WRITE = 0x07;
    final byte ACTIONTYPE_CMD24K_FW_UPGRADE = 0x08;
    final byte ACTIONTYPE_CMD_FW_FINISH = 0x09;
    final byte ACTIONTYPE_CMD_FW24k_FINISH = 0x0a;
    final byte ACTIONTYPE_CMD4K_FW_ERASE = 0x0B;
    final byte ACTIONTYPE_CMD4K_FW_WRITE = 0x0C;
    final byte ACTIONTYPE_CMD4K_FW_UPGRADE = 0x0D;
    final byte ACTIONTYPE_CMD_FW4k_FINISH = 0x0E;
    private TextView otaStatusInfo;
    private Spinner updateVersion;
    private Button readBloodPressure;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test);
        bandCommAgent = BandCommAgent.getInstance(this);
        bandCommAgent.setBluetoothSignalListener(mListener);
        EventBus.getDefault().register(this);
        initView();
        initListener();
        registerReceiver(mGattUpdateReceiver, makeGattUpdateIntentFilter());


     handler.postDelayed(new Runnable() {
         @Override
         public void run() {
             getFW.callOnClick();
         }
     },1000);

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onGetMessage(MsgBean bean) {
        bandCommAgent.appPushMessageToDevice(bean.getMsgType(), bean.getMsgTitle(), bean.getMsgContent());
    }

    private final BroadcastReceiver mGattUpdateReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            final String action = intent.getAction();
            if (BandCommAgent.ACTION_DATA_WRITE.equals(action)) {
                int status = intent.getIntExtra("value", 0);
                byte[] data = intent.getByteArrayExtra("data");
                if (spinner_doingfun_sel == false) {
                    Log.i("SYD_OTA", "Send PacketID:" + SendPacketID + "  AllNum:" + SendPacketAllNum);
                    OTA_Process_doing(status, data);
                } else {
                    Log.i("SYD_OTA", "Receive PacketID:" + SendPacketID + "  AllNum:" + SendPacketAllNum);
                    new Handler().postDelayed(new Runnable() {
                        public void run() {
                            //execute the task
                            bandCommAgent.receiveData();
                        }
                    }, 800);
                }

            } else if (BandCommAgent.ACTION_DATA_READ.equals(action)) {
                Log.i("SYD_OTA", "ACTION_DATA_READ");
                if (spinner_doingfun_sel == true) {
                    int status = intent.getIntExtra("value", 0);
                    byte[] data = intent.getByteArrayExtra("data");
                    Log.i("SYD_OTA", "Send and read PacketID:" + SendPacketID + "  AllNum:" + SendPacketAllNum);
                    Log.i("SYD_OTA", "ACTION_DATA_READ Data--->data:" + Arrays.toString(data));
                    Log.i("SYD_OTA", "ACTION_DATA_READ Data--->status:" + status);
                    Log.i("SYD_OTA", "ACTION_DATA_READ Data--->actionType:" + actionType);
                    OTA_Process_doing(status, data);
                }
            }
        }
    };

    private static IntentFilter makeGattUpdateIntentFilter() {
        final IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(BandCommAgent.GATT_CONNECTED);
        intentFilter.addAction(BandCommAgent.GATT_DISCONNECTED);
        intentFilter.addAction(BandCommAgent.GATT_SERVICES_DISCOVERED);
        intentFilter.addAction(BandCommAgent.ACTION_DATA_CHANGE);
        intentFilter.addAction(BandCommAgent.ACTION_DATA_READ);
        intentFilter.addAction(BandCommAgent.ACTION_DATA_WRITE);
        intentFilter.addAction(BandCommAgent.ACTION_RSSI_READ);
        return intentFilter;
    }

    private void initView() {
        App.isFirst=true;
        recyclerView = findViewById(R.id.rv);
        setParameter = findViewById(R.id.btn_set_parameter);
        takePhoto = findViewById(R.id.btn_take_photo);
        getBattery = findViewById(R.id.btn_get_battery);
        clearData = findViewById(R.id.btn_clear_data);
        getDeviceMacAddress = findViewById(R.id.btn_get_device_mac_address);
        getFW = findViewById(R.id.btn_get_fw);
        getDeviceTime = findViewById(R.id.btn_get_device_time);
        btn_sedentary_alarm = findViewById(R.id.btn_sedentary_alarm);
        setUserInfo = findViewById(R.id.btn_set_user_info);
        getSportAndSleepData = findViewById(R.id.btn_get_sport_and_sleep_data);
        getSportAndSleepDataAllDay = findViewById(R.id.btn_get_sport_and_sleep_data_all_day);
        findDevice = findViewById(R.id.btn_find_device);
        getRealStep = findViewById(R.id.btn_get_real_step);
        readRealHeartRate = findViewById(R.id.btn_read_real_heart_rate);
        appPushMsgToDevice = findViewById(R.id.btn_app_push_msg_to_device);
        setDeviceTime = findViewById(R.id.btn_set_device_time);
        unbindMac = findViewById(R.id.btn_unbind_mac);
        etWeek = findViewById(R.id.et_week);
        etHour = findViewById(R.id.et_hour);
        etAllDayWeek = findViewById(R.id.et_all_day_week);
        etStartHour = findViewById(R.id.et_start_hour);
        etEndHour = findViewById(R.id.et_end_hour);
        etDetectionTime = findViewById(R.id.et_detection_time);
        etRepeatCycle = findViewById(R.id.et_repeat_cycle);
        btnControlDevice = findViewById(R.id.btn_control_device);
        closeDevice = findViewById(R.id.btn_close_device);
        restartDevice = findViewById(R.id.btn_restart_device);
        openRemind = findViewById(R.id.btn_open_remind);
        remindType = findViewById(R.id.sp_remind_type);
        etMessageTitle = findViewById(R.id.et_message_title);
        etMessageContent = findViewById(R.id.et_message_content);
        messageType = findViewById(R.id.sp_message_type);
        progressBar = findViewById(R.id.progressbar);
        checkOTAFile = findViewById(R.id.btn_check_ota_file);
        otaUpdate = findViewById(R.id.btn_ota_update);
        etFilePath = findViewById(R.id.et_file_path);
        progressInfo = findViewById(R.id.tv_progress_info);
        otaStatusInfo = findViewById(R.id.tv_status_info);
        updateVersion = findViewById(R.id.sp_update_version);
        readBloodPressure = findViewById(R.id.btn_read_blood_pressure);
        initRecyclerView();

        etFilePath.setText(App.filepath);

    }

    private void initRecyclerView() {
        recyclerView.setHasFixedSize(true);
        messageAdapter = new MessageAdapter();
        recyclerView.setAdapter(messageAdapter);
    }

    private void initListener() {
        setParameter.setOnClickListener(mOnClickListener);
        takePhoto.setOnClickListener(mOnClickListener);
        getBattery.setOnClickListener(mOnClickListener);
        clearData.setOnClickListener(mOnClickListener);
        getDeviceMacAddress.setOnClickListener(mOnClickListener);
        getFW.setOnClickListener(mOnClickListener);
        getDeviceTime.setOnClickListener(mOnClickListener);
        btn_sedentary_alarm.setOnClickListener(mOnClickListener);
        setUserInfo.setOnClickListener(mOnClickListener);
        getSportAndSleepData.setOnClickListener(mOnClickListener);
        getSportAndSleepDataAllDay.setOnClickListener(mOnClickListener);
        findDevice.setOnClickListener(mOnClickListener);
        getRealStep.setOnClickListener(mOnClickListener);
        readRealHeartRate.setOnClickListener(mOnClickListener);
        appPushMsgToDevice.setOnClickListener(mOnClickListener);
        setDeviceTime.setOnClickListener(mOnClickListener);
        unbindMac.setOnClickListener(mOnClickListener);
        btnControlDevice.setOnClickListener(mOnClickListener);
        closeDevice.setOnClickListener(mOnClickListener);
        restartDevice.setOnClickListener(mOnClickListener);
        openRemind.setOnClickListener(mOnClickListener);
        checkOTAFile.setOnClickListener(mOnClickListener);
        otaUpdate.setOnClickListener(mOnClickListener);
        readBloodPressure.setOnClickListener(mOnClickListener);
        remindType.setOnItemSelectedListener(mOnItemSelectedListener);
        messageType.setOnItemSelectedListener(mOnItemSelectedListener);
        updateVersion.setOnItemSelectedListener(mOnItemSelectedListener);
    }

    private View.OnClickListener mOnClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.btn_set_parameter:
                    setDeviceParameter();
                    break;
                case R.id.btn_take_photo:
                    bandCommAgent.takePhoto(true);
                    break;
                case R.id.btn_get_battery:
                    bandCommAgent.getDeviceBattery();
                    break;
                case R.id.btn_clear_data:
                    bandCommAgent.clearData();
                    break;
                case R.id.btn_get_device_mac_address:
                    bandCommAgent.getDeviceMacAddress();
                    break;
                case R.id.btn_get_fw:
                    bandCommAgent.getDeviceFirmwareVersion();
                    break;
                case R.id.btn_get_device_time:
                    bandCommAgent.readDeviceTime();
                    break;
                case R.id.btn_sedentary_alarm:
                    setSedentaryAlarm();
                    break;
                case R.id.btn_set_user_info:
                    setUserInfo();
                    break;
                case R.id.btn_get_sport_and_sleep_data:
                    if (!etWeek.getText().toString().isEmpty() && !etHour.getText().toString().isEmpty()) {
                        int week = Integer.parseInt(etWeek.getText().toString());
                        int hour = Integer.parseInt(etHour.getText().toString());
                        if ((week < 8 && week > 0) && (hour >= 0 && hour < 24)) {
                            bandCommAgent.readSportAndSleepData(week, hour);
                            etWeek.setText("");
                            etHour.setText("");
                        } else {
                            Toast.makeText(TestActivity.this, "请输入正确的查询时间", Toast.LENGTH_SHORT).show();
                            return;
                        }
                    } else {
                        Toast.makeText(TestActivity.this, "请输入查询时间", Toast.LENGTH_SHORT).show();
                        return;
                    }

                    break;
                case R.id.btn_get_sport_and_sleep_data_all_day:
                    if (!etAllDayWeek.getText().toString().isEmpty()) {
                        int week = Integer.parseInt(etAllDayWeek.getText().toString());
                        if (week < 8 && week > 0) {
                            bandCommAgent.readSportAndSleepData(week);
                            etAllDayWeek.setText("");
                        } else {
                            Toast.makeText(TestActivity.this, "请输入正确的查询时间", Toast.LENGTH_SHORT).show();
                            return;
                        }
                    } else {
                        Toast.makeText(TestActivity.this, "请输入查询时间", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    break;
                case R.id.btn_find_device:
                    bandCommAgent.findDevice(true);
                    break;
                case R.id.btn_get_real_step:
                    bandCommAgent.getDeviceRealStep();
                    break;
                case R.id.btn_read_real_heart_rate:
                    bandCommAgent.readRealHeartRate(true, 1);
                    break;
                case R.id.btn_app_push_msg_to_device:
                    String messageTitle = etMessageTitle.getText().toString();
                    String messageContent = etMessageContent.getText().toString();
                    if (!TextUtils.isEmpty(messageContent) && !TextUtils.isEmpty(messageTitle)) {
                        // bandCommAgent.appPushMessageToDevice(2, "悦步", "哈哈哈哈哈哈哈哈哈哈哈");
                        bandCommAgent.appPushMessageToDevice(msgType, messageTitle, messageContent);
                    } else {
                        Toast.makeText(TestActivity.this, "请输入正确的字符", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    break;
                case R.id.btn_set_device_time:
                    bandCommAgent.setDeviceTime(System.currentTimeMillis());
                    break;
                case R.id.btn_unbind_mac:
                    SPUtils.getInstance(TestActivity.this).clear();
                    break;
                case R.id.btn_control_device:
                    bandCommAgent.openAllPushSwitch();
                    // bandCommAgent.setPushTypeSwitch(PushType.PUSH_TYPE_CALL);
                    break;
                case R.id.btn_close_device:
                    bandCommAgent.closeDevice();
                    break;
                case R.id.btn_restart_device:
                    bandCommAgent.restartDevice();
                    break;
                case R.id.btn_open_remind:
                    switch (selectedType) {
                        case 0:
                            bandCommAgent.setPushTypeSwitch(PushType.PUSH_TYPE_CALL);
                            break;
                        case 1:
                            bandCommAgent.setPushTypeSwitch(PushType.PUSH_TYPE_MESSAGE);
                            break;
                        case 2:
                            bandCommAgent.setPushTypeSwitch(PushType.PUSH_TYPE_MAIL);
                            break;
                        case 3:
                            bandCommAgent.setPushTypeSwitch(PushType.PUSH_TYPE_SCHEDULE);
                            break;
                        case 4:
                            bandCommAgent.setPushTypeSwitch(PushType.PUSH_TYPE_LOW);
                            break;
                        case 5:
                            bandCommAgent.setPushTypeSwitch(PushType.PUSH_TYPE_FACEBOOK);
                            break;
                        case 6:
                            bandCommAgent.setPushTypeSwitch(PushType.PUSH_TYPE_TWITTER);
                            break;
                        case 7:
                            bandCommAgent.setPushTypeSwitch(PushType.PUSH_TYPE_WECHAT);
                            break;
                        case 8:
                            bandCommAgent.setPushTypeSwitch(PushType.PUSH_TYPE_QQ);
                            break;
                        case 9:
                            bandCommAgent.setPushTypeSwitch(PushType.PUSH_TYPE_SKYPE);
                            break;
                        case 10:
                            bandCommAgent.setPushTypeSwitch(PushType.PUSH_TYPE_LINE);
                            break;
                        case 11:
                            bandCommAgent.setPushTypeSwitch(PushType.PUSH_TYPE_WHATSAPP);
                            break;
                        case 12:
                            bandCommAgent.setPushTypeSwitch(PushType.PUSH_TYPE_MISSED_CALL);
                            break;
                        case 13:
                            bandCommAgent.setPushTypeSwitch(PushType.PUSH_TYPE_MISSED_MESSAGE);
                            break;
                        case 14:
                            bandCommAgent.setPushTypeSwitch(PushType.PUSH_TYPE_NAME);
                            break;

                    }
                    break;
                case R.id.btn_check_ota_file:
                    Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                    intent.setType("*/*");
                    intent.addCategory(Intent.CATEGORY_OPENABLE);
                    startActivityForResult(intent, REQUEST_GET_FILE);
                    break;
                case R.id.btn_ota_update:

                    messageAdapter.addData("开始升级OTA:" );
                    recyclerView.smoothScrollToPosition(messageAdapter.getData().size() - 1);

                    String filePath = etFilePath.getText().toString();
//                    filePath =" rq345345423452345";
                    if (!TextUtils.isEmpty(filePath)) {
//                        File file = new File(filePath);
//                        if (file.length() < 1024) {
//                            Toast.makeText(TestActivity.this, "文件太小，请重新选择！", Toast.LENGTH_SHORT).show();
//                            return;
//                        }
                        //发指令进入OTA模式
                        bandCommAgent.entryOTAMode();
                        Log.i("SYD_OTA", "OTA Speed BLE");
                        try {
                            Thread.sleep(1500);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        OTA_Process_Start(filePath);
                    } else {
                        Toast.makeText(TestActivity.this, "请选择文件路径", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    break;
                case R.id.btn_read_blood_pressure:
                    bandCommAgent.readCurrentBloodpressure(true, 1);
                    break;
            }
        }
    };

    private void OTA_Process_Start(String filePath) {
        ReadData = ReadOTAFileBinary(filePath);
        for (int i = 0; i < ReadData.length; i++) {
            int CC = ReadData[i];
            CC &= 0x000000FF;
            CRC += CC;
            CRC = CRC & 0x0000FFFF;
        }
        Log.i("SYD_OTA", "OTA_Process_Start CRC ==>" + CRC);
        OTA_Erase_Flash();
    }


    //擦除空间
    private void OTA_Erase_Flash() {
        actionType = ACTIONTYPE_CMD_FW_ERASE;
        byte[] WriteData = new byte[2];
        WriteData[0] = 0x16;
        WriteData[1] = 0x00;
        Log.i("SYD_OTA", "OTA_Erase_Flash Start");
        bandCommAgent.sendData(WriteData);
    }

    private byte[] ReadOTAFileBinary(String filepath) {

//      return    readFile();

        File file = new File(filepath);
        try {
            FileInputStream fis = new FileInputStream(file);
            int length = fis.available();
            byte[] BinaryData = new byte[length];
            BLELogUtil.i("升级文件的长度：" + Formatter.formatFileSize(this, Long.valueOf(length)));
            fis.read(BinaryData);

            fis.close();
            return BinaryData;
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        byte[] BinaryData = new byte[]{0x01, 0x01};
        return BinaryData;
    }

    byte[] readFile() {
        byte[] buffer = null;
        InputStream is = null;
        try {
            is = getAssets().open("update.bin");

            int lenght = is.available();
            //工具类 根据文件大小自动转化为KB, MB, GB  );
            BLELogUtil.i("升级文件的长度：" + Formatter.formatFileSize(this, Long.valueOf(lenght)));
            buffer = new byte[lenght];
            is.read(buffer);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return buffer;
    }

    private void OTA_Process_doing(int status, final byte[] data) {
        if (actionType == ACTIONTYPE_CMD_FW_ERASE) {
            if (updateType == 0) {
                Toast.makeText(this, "请稍等，擦除空间中！", Toast.LENGTH_LONG).show();
                new Handler().postDelayed(new Runnable() {
                    public void run() {
                        //execute the task
                        OTA_Write_Flash_Start_V30(data);
                    }
                }, 10000);
            } else if (updateType == 1) {
                Toast.makeText(this, "请稍等，擦除空间中！", Toast.LENGTH_LONG).show();
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        //execute the task
                        OTA_Write_Flash_Start();
                    }
                }, 10000);
            }

        } else if (actionType == ACTIONTYPE_CMD_FW_WRITE) {
            OTA_Write_All_Flash(status);
        } else if (actionType == ACTIONTYPE_CMD_FW_UPGRADE) {
            if (updateType == 0) {
                OTA_Upgrade_Flash_V30(ReadData.length, CRC);
            } else if (updateType == 1) {
                OTA_Upgrade_Flash_V20(ReadData.length, CRC);
            }
        } else if (actionType == ACTIONTYPE_CMD_FW_FINISH) {
            if (((data[0] & 0xFF) == EVT_COMMAND_COMPLETE) & ((data[3] & 0xFF) == ERR_COMMAND_FAILED)) {
                ShowStatus("OTA失败, 请重新OTA");
                messageAdapter.addData("OTA失败, 请重新OTA");
            } else {
                ShowStatus("OTA完成, 复位设备中");
                messageAdapter.addData("OTA完成, 复位设备中");

            }
            recyclerView.smoothScrollToPosition(messageAdapter.getData().size() - 1);
            OTA_Process_init();
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    App.isFinsh =true;
                    finish();
                }
            },1000);


        } else if (actionType == ACTIONTYPE_CMD_FW_WRITE_START) {
            OTA_Write_Section_All_Flash(status);
        } else if (actionType == ACTIONTYPE_CMD_FW_WRITE_END) {
            OTA_Write_Flash_Continue_V30(data);
        }
    }

    public void OTA_Upgrade_Flash_V30(int Size, int CRC) {
        Log.i("SYD_OTA", "OTA_Upgrade_Flash CRC_V30:" + CRC + "Size" + Size);
        byte[] WriteData = new byte[8];
        WriteData[0] = 0x15;
        WriteData[1] = 0x04;
        WriteData[2] = (byte) (Size & 0x000000FF);
        WriteData[3] = (byte) ((Size & 0x0000FF00) >> 8);
        WriteData[4] = (byte) ((Size & 0x00FF0000) >> 16);
        WriteData[5] = (byte) ((Size & 0xFF000000) >> 24);
        WriteData[6] = (byte) (CRC & 0x000000FF);
        WriteData[7] = (byte) ((CRC & 0x0000FF00) >> 8);
        actionType = ACTIONTYPE_CMD_FW_FINISH;
        spinner_doingfun_sel = true;
        bandCommAgent.sendData(WriteData);
    }

    public void OTA_Write_Section_All_Flash(int status) {

        int srcPos = SendPacketID * MAX_TRANS_COUNT_V30;
        final byte[] dataPacket = new byte[MAX_TRANS_COUNT_V30];
        if (status == 0) {
            if (SendPacketID == SendPacketAllNum) {
                actionType = 0;
            } else {
                if (SendPacketID == (SendPacketAllNum - 1)) {
                    System.arraycopy(ReadData, srcPos, dataPacket, 0, (ReadData.length - srcPos));//last a packet
                    actionType = ACTIONTYPE_CMD_FW_UPGRADE;//发送完最后一包了
                } else {
                    System.arraycopy(ReadData, srcPos, dataPacket, 0, MAX_TRANS_COUNT_V30);//other packet except first and last packet
                }
                OTA_Write_Secton_Flash(dataPacket, SendPacketID);
                SendPacketID += 1;
            }

            if (SendPacketID % MAX_TRANS_SECTIONALL_PACKET_COUNT == 0) {
                actionType = ACTIONTYPE_CMD_FW_WRITE_END;
                spinner_doingfun_sel = true;
                Log.i("SYD_OTA", "Section:" + Integer.toString(SendPacketID / MAX_TRANS_SECTIONALL_PACKET_COUNT));
            }
            // 创建一个数值格式化对象
            NumberFormat numberFormat = NumberFormat.getInstance();
            // 设置精确到小数点后2位
            numberFormat.setMaximumFractionDigits(2);
            String result = numberFormat.format((float) SendPacketID / (float) SendPacketAllNum * 100) + "%";
            ShowStatus("请勿中断，OTA进行中 ...");
            ShowStatusPercentage(result);
            ShowProgressBar((int) ((float) SendPacketID / (float) SendPacketAllNum * 100));
        } else {
            ShowStatus("OTA更新失败,请重试");
            finish();
        }
    }

    public void OTA_Write_Secton_Flash(byte[] ProgramData, int Address) {
        bandCommAgent.sendData(ProgramData, BluetoothGattCharacteristic.WRITE_TYPE_NO_RESPONSE);//写入第一包
    }

    public void OTA_Write_Flash_Start_V30(byte[] data) {
        Log.i("SYD_OTA", "OTA_Write_Flash_Start_V30");

        SendPacketAllNum = ReadData.length / MAX_TRANS_COUNT_V30;
        if (ReadData.length % MAX_TRANS_COUNT_V30 != 0)
            SendPacketAllNum += 1;
        OTA_Write_Flash_Continue_V30(data);
        // 创建一个数值格式化对象
        NumberFormat numberFormat = NumberFormat.getInstance();
        // 设置精确到小数点后2位
        numberFormat.setMaximumFractionDigits(2);

        String result = numberFormat.format((float) SendPacketID / (float) SendPacketAllNum * 100) + "%";
        ShowStatus("请勿中断，OTA进行中 ...");
        ShowStatusPercentage(result);
        ShowProgressBar((int) ((float) SendPacketID / (float) SendPacketAllNum * 100));
    }

    public void OTA_Write_Flash_Continue_V30(byte[] data) {
        Log.i("SYD_OTA", "OTA_Write_Flash_Continue");
        actionType = ACTIONTYPE_CMD_FW_WRITE_START;
        if ((SendSectionID != 0) && (data != null)) {
            int check = ((data[7] & 0xff) << 8) | (data[6] & 0xff);

            if ((check & 0x0000ffff) != (SECTION_CRC & 0x0000ffff)) {
                Log.i("SYD_OTA", "SECTION resend:" + SendSectionID + " check device:" + check + " check app:" + SECTION_CRC);
                SendSectionID -= 1;
                SendPacketID = MAX_TRANS_SECTIONALL_PACKET_COUNT * SendSectionID;
            }
        }

        if ((SendPacketAllNum - SendPacketID) >= MAX_TRANS_SECTIONALL_PACKET_COUNT)
            MAX_TRANS_SECTIONALL_SIZE = MAX_TRANS_SECTIONALL_COUNT;
        else
            MAX_TRANS_SECTIONALL_SIZE = ReadData.length % MAX_TRANS_SECTIONALL_COUNT;

        SECTION_CRC = 0;
        for (int i = 0; i < MAX_TRANS_SECTIONALL_SIZE; i++) {
            int CC = ReadData[SendSectionID * MAX_TRANS_SECTIONALL_COUNT + i];
            CC &= 0x000000FF;
            SECTION_CRC += CC;
        }

        Log.i("SYD_OTA", "SECTION_CRC ==>" + SECTION_CRC);
        OTA_Write_Flash_section_start(SECTION_CRC, MAX_TRANS_SECTIONALL_SIZE, SendSectionID);
        SendSectionID += 1;

        spinner_doingfun_sel = false;
    }

    public void OTA_Write_Flash_section_start(int check, int size, int Address) {
        byte[] WriteData = new byte[10];
        Address = Address * MAX_TRANS_SECTIONALL_COUNT;

        WriteData[0] = 0x14;
        WriteData[1] = 0x13;
        WriteData[2] = (byte) (Address & 0x000000FF);
        WriteData[3] = (byte) ((Address & 0x0000FF00) >> 8);
        WriteData[4] = (byte) ((Address & 0x00FF0000) >> 16);
        WriteData[5] = (byte) ((Address & 0xFF000000) >> 24);
        WriteData[6] = (byte) (size & 0x000000FF);
        WriteData[7] = (byte) ((size & 0x0000FF00) >> 8);
        WriteData[8] = (byte) (check & 0x000000FF);
        WriteData[9] = (byte) ((check & 0x0000FF00) >> 8);
        bandCommAgent.sendData(WriteData);//写入第一包
    }

    void OTA_Process_init() {
        SendPacketID = 0;
        SendPacketAllNum = 0;
        CRC = 0;
        ReadData = null;
        actionType = 0;
        SendSectionID = 0;
        SECTION_CRC = 0;
        MAX_TRANS_SECTIONALL_SIZE = 0;
    }

    private void ShowStatus(final String status) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                otaStatusInfo.setText(status);
            }
        });
    }

    public void ShowStatusPercentage(final String status) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                progressInfo.setText(status);
            }
        });
    }


    private void OTA_Upgrade_Flash_V20(int Size, int CRC) {
        Log.i("SYD_OTA", "OTA_Upgrade_Flash CRC_V20:" + CRC + "Size" + Size);
        byte[] WriteData = new byte[8];
        WriteData[0] = 0x15;
        WriteData[1] = 0x04;
        WriteData[2] = (byte) (Size & 0x000000FF);
        WriteData[3] = (byte) ((Size & 0x0000FF00) >> 8);
        WriteData[4] = (byte) ((Size & 0x00FF0000) >> 16);
        WriteData[5] = (byte) ((Size & 0xFF000000) >> 24);
        WriteData[6] = (byte) (CRC & 0x000000FF);
        WriteData[7] = (byte) ((CRC & 0x0000FF00) >> 8);
        actionType = ACTIONTYPE_CMD_FW_FINISH;
        spinner_doingfun_sel = true;
        bandCommAgent.sendData(WriteData);
    }

    private void OTA_Write_All_Flash(int status) {
        int srcPos = SendPacketID * MAX_TRANS_COUNT;

        final byte[] dataPacket = new byte[MAX_TRANS_COUNT];
        if (status == 0) {
            if (SendPacketID == SendPacketAllNum) {
                actionType = 0;
            } else {
                if (SendPacketID == (SendPacketAllNum - 1)) {
                    System.arraycopy(ReadData, srcPos, dataPacket, 0, (ReadData.length - srcPos));//last a packet
                    actionType = ACTIONTYPE_CMD_FW_UPGRADE;//发送完最后一包了
                } else {
                    System.arraycopy(ReadData, srcPos, dataPacket, 0, MAX_TRANS_COUNT);//other packet except first and last packet
                }
                OTA_Write_Flash(dataPacket, SendPacketID);
                SendPacketID += 1;
            }
            // 创建一个数值格式化对象
            NumberFormat numberFormat = NumberFormat.getInstance();
            // 设置精确到小数点后2位
            numberFormat.setMaximumFractionDigits(2);
            String result = numberFormat.format((float) SendPacketID / (float) SendPacketAllNum * 100) + "%";
            ShowStatus("请勿中断，OTA进行中 ...");
            ShowStatusPercentage(result);
            ShowProgressBar((int) ((float) SendPacketID / (float) SendPacketAllNum * 100));
        } else {
            ShowStatus("OTA更新失败,请重试");
        }
    }

    private void OTA_Write_Flash_Start() {
        byte[] dataPacket = new byte[MAX_TRANS_COUNT];
        Log.i("SYD_OTA", "OTA_Write_Flash_Start");
        actionType = ACTIONTYPE_CMD_FW_WRITE;
        SendPacketAllNum = ReadData.length / MAX_TRANS_COUNT;
        if (ReadData.length % MAX_TRANS_COUNT != 0)
            SendPacketAllNum += 1;

        System.arraycopy(ReadData, 0, dataPacket, 0, MAX_TRANS_COUNT);

        OTA_Write_Flash(dataPacket, SendPacketID);
        SendPacketID += 1;

        // 创建一个数值格式化对象
        NumberFormat numberFormat = NumberFormat.getInstance();
        // 设置精确到小数点后2位
        numberFormat.setMaximumFractionDigits(2);
        String result = numberFormat.format((float) SendPacketID / (float) SendPacketAllNum * 100) + "%";
        ShowStatus("请勿中断，OTA进行中 ...");
        ShowStatusPercentage(result);
        ShowProgressBar((int) ((float) SendPacketID / (float) SendPacketAllNum * 100));
    }

    private void ShowProgressBar(int i) {
        progressBar.setProgress(i);
    }

    public void OTA_Write_Flash(byte[] ProgramData, int Address) {
        byte[] WriteData = new byte[20];
        Address = Address * MAX_TRANS_COUNT;
        WriteData[0] = 0x17;
        WriteData[1] = 0x13;
        WriteData[2] = (byte) (Address & 0x000000FF);
        WriteData[3] = (byte) ((Address & 0x0000FF00) >> 8);
        WriteData[4] = (byte) ProgramData.length;

        int i = 0;
        for (i = 0; i < ProgramData.length; i++) {
            WriteData[i + 5] = ProgramData[i];
        }
        bandCommAgent.sendData(WriteData);//写入第一包
    }

    private AdapterView.OnItemSelectedListener mOnItemSelectedListener = new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            switch (parent.getId()) {
                case R.id.sp_remind_type:
                    selectedType = position;
//                    Log.i(TAG, "onItemSelected: selectedType" + selectedType);
                    break;
                case R.id.sp_message_type:
                    msgType = position;
//                    Log.i(TAG, "onItemSelected:msgType " + msgType);
                    break;
                case R.id.sp_update_version:
                    updateType = position;
                    break;


            }

        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {

        }
    };

    private void setDeviceParameter() {
        DeviceParameterBean bean = new DeviceParameterBean();
        bean.setTimeType(1);
        bean.setTemperature(0);
        bean.setBrightScreenToggle(255);
        bean.setSomehowTheScreen(1);
        bean.setMeasurementType(1);
        bean.setShockToggle(1);
        bean.setBrightScreenToggle(1);
        bean.setLanguageType(0);
        bean.setNotDisturbMode(0);
        bean.setNotDisturbStartHour(0);
        bean.setNotDisturbStartMinute(0);
        bean.setNotDisturbEndHour(8);
        bean.setNotDisturbEndMinute(0);
        bean.setScreenOrientation(0);
        bean.setDateDispalyType(1);
        bandCommAgent.setDeviceParameter(bean);
    }

    //设置久坐闹钟
    private void setSedentaryAlarm() {
        if (!TextUtils.isEmpty(etStartHour.getText().toString())
                && !TextUtils.isEmpty(etEndHour.getText().toString())
                && !TextUtils.isEmpty(etDetectionTime.getText().toString())
                && !TextUtils.isEmpty(etRepeatCycle.getText().toString())) {

            int startHour = Integer.parseInt(etStartHour.getText().toString());
            int endHour = Integer.parseInt(etEndHour.getText().toString());
            int detectionTime = Integer.parseInt(etDetectionTime.getText().toString());
            int repeatCycle = Integer.parseInt(etRepeatCycle.getText().toString());

            if ((startHour >= 0 && startHour < 24)
                    && (endHour >= 0 && endHour < 24)
                    && (detectionTime > 0 && detectionTime < 24)
                    && (repeatCycle >= 0 && repeatCycle < 8)) {
                SedentaryAlarmBean bean = new SedentaryAlarmBean();
                bean.setIsOpen(1);
                bean.setStartHour(startHour);
                bean.setEndHour(endHour);
                bean.setDetectionTime(detectionTime);
                bean.setRepeatCycle(repeatCycle);
                bandCommAgent.setSedentaryAlarm(bean);
                etStartHour.setText("");
                etEndHour.setText("");
                etDetectionTime.setText("");
                etRepeatCycle.setText("");
            } else {
                Toast.makeText(TestActivity.this, "有不符合规范的数据", Toast.LENGTH_SHORT).show();
                return;
            }

        } else {
            Toast.makeText(TestActivity.this, "请输入正确的数据", Toast.LENGTH_SHORT).show();
            return;
        }

    }

    //设置用户信息
    private void setUserInfo() {
        PersonalInfoBean bean = new PersonalInfoBean();
        bean.setAlarm1_open(1);
        bean.setAlarm2_open(0);
        bean.setAlarm3_open(0);
        bean.setAlarm4_open(0);
        bean.setAlerm1_hour(10);
        bean.setAlerm2_hour(1);
        bean.setAlerm3_hour(1);
        bean.setAlerm4_hour(1);
        bean.setAlerm1_minute(48);
        bean.setAlerm2_minute(35);
        bean.setAlerm3_minute(35);
        bean.setAlerm4_minute(35);
        bean.setAlerm1_weeks(255);
        bean.setAlerm2_weeks(7);
        bean.setAlerm3_weeks(7);
        bean.setAlerm4_weeks(7);
        bean.setAlerm1_reminding(1);
        bean.setAlerm2_reminding(1);
        bean.setAlerm3_reminding(1);
        bean.setAlerm4_reminding(1);
        bean.setUser_sex(1);
        bean.setUser_height(170);
        bean.setUser_weight(60);
        bean.setUser_sleep_start_hour(22);
        bean.setUser_sleep_start_mins(0);
        bean.setUser_sleep_end_hour(8);
        bean.setUser_sleep_end_mins(0);
        bean.setUser_stride_walk(0);
        bean.setUser_stride_run(0);
        bean.setUser_step_target(10000);
        bandCommAgent.setPersonalInfo(bean);
    }

    private  Handler handler=new Handler();

    private BluetoothSignalListener mListener = new BluetoothSignalListener() {
        @Override
        public void onConnected(String mac) {

        }

        @Override
        public void onConnectionFailed(BLEException bleException, int status) {

        }


        @Override
        public void onDisconnect() {

        }

        @Override
        public void onReceiveMacAddress(String macAddress) {
            messageAdapter.addData("mac地址:" + macAddress);
            recyclerView.smoothScrollToPosition(messageAdapter.getData().size() - 1);
        }

        @Override
        public void onReceiveDeviceFirmwareVersion(String versionCode) {
            String da =versionCode.replace("-",".").replace("v", "").replace("V", "");
            BLELogUtil.i("固件版本:" + da  +"  "  +App.ver);
            messageAdapter.addData("固件版本:" + versionCode.replace("-",".") +"   最新版本："+App.ver);
            if(Float.parseFloat(da) < Float.parseFloat(App.ver)){
                messageAdapter.addData("需要升级" );
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        mOnClickListener.onClick(otaUpdate);
                    }
                },1000);

            }else{
                messageAdapter.addData("不需要升级" );
                App.isFinsh=true;
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        finish();
                    }
                },2000);

            }
            recyclerView.smoothScrollToPosition(messageAdapter.getData().size() - 2);
        }

        @Override
        public void onSetDeviceTimeResponse(boolean isSuccess) {
            messageAdapter.addData("设置手环时间:" + isSuccess);
            recyclerView.smoothScrollToPosition(messageAdapter.getData().size() - 1);

        }

        @Override
        public void onReadDeviceTime(DeviceTimeBean bean) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy年:MM月:dd日:HH时:mm分:ss秒");
            String format = sdf.format(new Date(bean.getDeviceTime()));
            messageAdapter.addData("读取手环时间" + format + "星期" + bean.getWeek());
            recyclerView.smoothScrollToPosition(messageAdapter.getData().size() - 1);
        }


        @Override
        public void onClearDataResponse(boolean isSuccess) {
            messageAdapter.addData("清除数据" + isSuccess);
            recyclerView.smoothScrollToPosition(messageAdapter.getData().size() - 1);

        }

        @Override
        public void onSetPersonalInfoResponse(boolean isSuccess) {
            messageAdapter.addData("设置用户信息" + isSuccess);
            recyclerView.smoothScrollToPosition(messageAdapter.getData().size() - 1);

        }

        @Override
        public void onGetDeviceBattery(String battery) {
            messageAdapter.addData("电量:" + battery);
            recyclerView.smoothScrollToPosition(messageAdapter.getData().size() - 1);

        }

        @Override
        public void onSetSedentaryAlarm(boolean isSuccess) {
            messageAdapter.addData("设置久坐提醒" + isSuccess);
            recyclerView.smoothScrollToPosition(messageAdapter.getData().size() - 1);
        }

        @Override
        public void onTakePhotoSuccess() {
            messageAdapter.addData("打开相机");
            recyclerView.smoothScrollToPosition(messageAdapter.getData().size() - 1);
        }

        @Override
        public void onSetDeviceParameterResponse(boolean isSuccess) {
            messageAdapter.addData("设置手环参数" + isSuccess);
            recyclerView.smoothScrollToPosition(messageAdapter.getData().size() - 1);
        }

        @Override
        public void onFindDeviceSuccess() {
            messageAdapter.addData("查找手环");
            recyclerView.smoothScrollToPosition(messageAdapter.getData().size() - 1);
        }

        @Override
        public void onReadDeviceRealStep(Long step) {
            messageAdapter.addData("实时步数数据" + step);
            recyclerView.smoothScrollToPosition(messageAdapter.getData().size() - 1);
        }

        @Override
        public void onReadDeviceSportAndSleepDataResponse(Long record_step_steps, int deepSleep, int lightSleep) {
            messageAdapter.addData("步数:" + record_step_steps + "深度睡眠:" + deepSleep + "分钟" + "浅度睡眠:" + lightSleep + "分钟");
            recyclerView.smoothScrollToPosition(messageAdapter.getData().size() - 1);
        }

        @Override
        public void onAppPushToDeviceResponse(boolean isSuccess) {
            messageAdapter.addData("推送消息" + isSuccess);
            recyclerView.smoothScrollToPosition(messageAdapter.getData().size() - 1);
        }

        @Override
        public void onControlDeviceResponse(boolean isSuccess) {
            messageAdapter.addData("设置提醒开关" + isSuccess);
            recyclerView.smoothScrollToPosition(messageAdapter.getData().size() - 1);
        }

        @Override
        public void onReadHeartRateResponse(int heartRate) {
            messageAdapter.addData("实时心率" + heartRate);
            recyclerView.smoothScrollToPosition(messageAdapter.getData().size() - 1);
        }

        @Override
        public void onReadBloodpressure(int highPressure, int lowPressure) {
            messageAdapter.addData("血压,高压:" + highPressure + "低压:" + lowPressure);
            recyclerView.smoothScrollToPosition(messageAdapter.getData().size() - 1);
        }
    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == REQUEST_GET_FILE) {
                Uri uri = data.getData();
                String path = "";
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    try {
                        path = getRealPathFromURI(uri);
                    } catch (Exception e) {
                        e.printStackTrace();
                        path = uri.getPath();
                    }
                } else if (Build.VERSION.SDK_INT == Build.VERSION_CODES.LOLLIPOP_MR1) {
                    path = uri.getPath();
                }
                etFilePath.setText(path);
            }
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            finish();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    public String getRealPathFromURI(Uri contentUri) throws Exception {
        String res = null;
        String[] proj = {MediaStore.Images.Media.DATA};
        Cursor cursor = getContentResolver().query(contentUri, proj, null, null, null);
        if (cursor.moveToFirst()) {
            int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            res = cursor.getString(column_index);
        }
        cursor.close();
        return res;
    }

    @Override
    protected void onDestroy() {
        unregisterReceiver(mGattUpdateReceiver);
        EventBus.getDefault().unregister(this);
        super.onDestroy();

    }

    @Override
    public void finish() {
        super.finish();
        BLELogUtil.i(" finish ----  ");
        bandCommAgent.disconnect();
    }
}
